package com.crazymaker.springcloud.base.filter;

import com.crazymaker.springcloud.base.service.impl.UserLoadService;
import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.crazymaker.springcloud.common.context.SessionHolder;
import com.crazymaker.springcloud.common.dto.UserDTO;
import com.crazymaker.springcloud.common.util.JsonUtil;
import com.crazymaker.springcloud.standard.redis.RedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.crazymaker.springcloud.common.context.SessionHolder.G_USER;

@Slf4j
public class RedisSessionFilter extends OncePerRequestFilter
{


    UserLoadService userLoadService;
    RedisRepository redisRepository;

    public RedisSessionFilter(UserLoadService userLoadService, RedisRepository redisRepository)
    {
        this.userLoadService = userLoadService;
        this.redisRepository = redisRepository;
    }

    private AuthenticationFailureHandler failureHandler =
            new SimpleUrlAuthenticationFailureHandler();


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException
    {

        String sid = SessionHolder.getSid();

        //todo : to delete
        if (!request.getSession().getId().equals(sid))
        {
            log.info("不相等" );
        }

        if (StringUtils.isEmpty(sid))
        {
            sid = request.getSession().getId();
            SessionHolder.setSid(sid);
            redisRepository.setSessionId(SessionHolder.getSessionSeed(), sid);
        }
        request.setAttribute(SessionConstants.ID, sid);
        HttpSession session = request.getSession();

        if (null == session.getAttribute(G_USER))
        {
            String uid = SessionHolder.getSessionSeed();
            UserDTO userDTO = null;

            if (SessionHolder.getSessionPrefix().equals(SessionConstants.SESSION_PRE))
            {
                //前台
                userDTO = userLoadService.loadFrontEndUser(Long.valueOf(uid));

            } else
            {
                //后台
                userDTO = userLoadService.loadBackEndUser(Long.valueOf(uid));

            }
            /**
             * 将用户信息缓存起来
             */
            session.setAttribute(G_USER, JsonUtil.pojoToJson(userDTO));
        }

        SessionHolder.setSession(session);
        SessionHolder.setRequest(request);

        filterChain.doFilter(request, response);
    }

    /**
     * 返回true代表不执行过滤器，false代表执行
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request)
    {
        if (null == SessionHolder.getSessionSeed())
        {
            return true;
        }

        if (request.getRequestURL().indexOf("/session/" ) > 0)
        {
            return true;
        }


        return false;
    }

}
